package com.qf.homework.utils;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseUtils {
   public static void detailCore(HttpServletResponse response){
        HttpServletResponse resp=null;
        resp=response;
        /* 允许跨域的主机地址 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        response.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        response.setHeader("Access-Control-Max-Age", "4200");
        /* 允许跨域的请求头 */
        response.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }
    public static <T> void success(HttpServletResponse response,ResponseEntity responseEntity,T data,Integer pageNum) throws IOException {
            detailCore(response);
            responseEntity.setData(data);
            responseEntity.setCode(200);
            responseEntity.setMsg("操作成功");
            if (pageNum!=null) {responseEntity.setPageNum(pageNum); }
            response.getWriter().print(JSONObject.toJSONString(responseEntity));

    }
    public static void fail(HttpServletResponse response,ResponseEntity responseEntity) throws IOException {
        detailCore(response);
        responseEntity.setCode(400);
        responseEntity.setMsg("操作失败");
        response.getWriter().write(JSONObject.toJSONString(responseEntity));
    }
}
